﻿using Microsoft.JSInterop;
using System.Collections.Concurrent;

namespace CardMaker.Library.Services; 

public class CardImageToUrlService:ICardImageToUrlService {
    private readonly IJSRuntime JS;
    private IJSObjectReference module = default!;
    private string? Img;//URL路径
    public CardImageToUrlService(IJSRuntime jsRuntime) => JS = jsRuntime;

    //初始化JS模块
    public async Task InitModuleAsync()
    {
        module = await JS!.InvokeAsync<IJSObjectReference>("import", "./js/getLocalImage.js");
    }

    public async Task<string> GenerateImageUrl(byte[] Image) {
        var dotnetImageStream = new DotNetStreamReference(new MemoryStream(Image)); 
        var img = await module.InvokeAsync<string>("streamToUrl", new object[1] { dotnetImageStream });
        return img;
    }//传入byte[]，得到URL，可以的被src=@Img引用，具体见CreateCard.razor
    public async Task RevokeUrl()
    {
        if (!string.IsNullOrEmpty(Img))
        {
            await module.InvokeVoidAsync("revokeUrl", Img);
            Img = string.Empty;
        }
    }//释放，目前还不确定在何处调用
    public async Task RevokeUrl(string img)
    {
        
        if (!string.IsNullOrEmpty(img))
        {
            await module.InvokeVoidAsync("revokeUrl", img);
            img = string.Empty;
        }
    }//释放，目前还不确定在何处调用
}